<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <title>Document</title>
  <style>

  </style>
</head>

<body>


  <button id="button">同意</button>
  <button id="goChrome">跳转获取code</button>
  <div id="request">qingqiu </div>

</body>
<script>
  const get = document.getElementById('button')
  const goChrome = document.getElementById('goChrome')
  const request = document.getElementById('request')

  get.addEventListener('click', function () {
    getCode()
    getUrlCode()
  })
  // 获取用户信息
  request.addEventListener('click', function () {
    axios.get('http://172.16.11.105:8101/api/userInfo?openId=oaBld49g1V5zVQhNZUX_ZKVaCmTE').then(res => {
      console.log(res)
    })
  })
  //获取code码
  goChrome.addEventListener('click', function () {
    var appid = 'wxdc7ed0f21b5d80bf&re'
    window.location.href =
      `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent('https://zg.particlesoft.info/frontenddev/api/OfficialAccounts')}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;

  })

  function getCode() { // 非静默授权，第一次有弹框
    var code = ''
    var local = window.location.href // 获取页面url
    var appid = 'wxdc7ed0f21b5d80bf&re'
    // 截取code
    if (code == null || code === '') { // 如果没有code，则去请求
      window.location.href =
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent('https://zg.particlesoft.info/frontenddev/index.html')}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
    } else {
      // 你自己的业务逻辑
    }
  }


  function getUrlCode() { // 截取url中的code方法
    var url = location.search
    console.log(location.search, 'url')
    var winUrl = url
    var theRequest = new Object()
    if (url.indexOf("?") != -1) {
      var str = url.substr(1)
      var strs = str.split("&")
      for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
      }
    }
    console.log(theRequest, 'therequest')
    return theRequest
  }
</script>


</html>